package nina.yiyou.salary.input.info

import nina.yiyou.salary.input.util.ExcelReadOpener
import nina.yiyou.salary.input.util.RowGroupValueGetter
import org.apache.poi.ss.usermodel.CellType
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.usermodel.XSSFCell
import org.apache.poi.xssf.usermodel.XSSFRow
import org.apache.poi.xssf.usermodel.XSSFSheet

/**
 * 读取考勤表
 *
 * @see AttendExcelV2Reader
 */
@Deprecated
class AttendExcelReader {

  AttendExcelReader(String excelPath) {
    _excelPath = excelPath
  }

  Map<String, Map> read() {
    Workbook workbook = new ExcelReadOpener(_excelPath).openXlsx()
    XSSFSheet sheet = workbook.getSheetAt(0)

    int lastRow = findLastRow(sheet)
    int dataStart = findColumn(sheet.getRow(3), '应出勤')

    Map<String, Map> result = (4..<lastRow).withIndex()
        .findAll { v, i -> i % 2 == 0 }
        .collect { v, i -> v as int }
        .collect { [sheet.getRow(it), sheet.getRow(it + 1)] }
        .collect { combine(it, { int offset -> dataStart + offset }) }
        .collectEntries { [it['工号'], it] }

    workbook.close()
    return result
  }

  private int findLastRow(XSSFSheet sheet) {
    int cursor = 4
    while (true) {
      XSSFCell cell = sheet.getRow(cursor).getCell(3)
      if (cell.cellTypeEnum == CellType.BLANK) {
        return cursor
      }
      cursor++
    }
  }

  private Map<String, ?> combine(List<XSSFRow> pair, Closure<Integer> dataCol) {
    def getValue = { int col -> new RowGroupValueGetter(pair, col).getValue() }

    def monthTotal = getValue(dataCol(0)) as double
    def totalProba = getValue(dataCol(2)) as double
    def wageProba = getValue(dataCol(3)) as double

    return [
        '工号'    : getValue(0),
        '姓名'    : getValue(1),
        '应出勤'   : monthTotal,
        '试用应出勤' : totalProba,
        '试用实际出勤': wageProba,
        '转正应出勤' : monthTotal - totalProba,
        '转正实际出勤': getValue(dataCol(1)) - wageProba,
        '全勤'    : getValue(dataCol(4)),
    ]
  }

  private int findColumn(XSSFRow row, String header) {
    for (int i = 0; i < row.lastCellNum; i++) {
      XSSFCell cell = row.getCell(i)
      if (cell.cellTypeEnum != CellType.STRING) {
        continue
      }
      if (cell.stringCellValue.contains(header)) {
        return i
      }
    }
    throw new IllegalStateException('找不到表头: ' + header)
  }

  private final String _excelPath
}
